package io.yunho.alg.snowflake.util;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.IdUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import sun.nio.ch.Net;

import javax.annotation.PostConstruct;

/**
 * @author: Jason
 * @date: 2020/12/28 13:05
 * @description:
 */
@Slf4j
@Component
public class IdSnowFlakeUtil {
    private long workerId = 0;
    private long datacenterId = 1;
    private Snowflake snowflake = IdUtil.createSnowflake(workerId,datacenterId);

    @PostConstruct
    public void init(){
        try {
            workerId = NetUtil.ipv4ToLong(NetUtil.getLocalhostStr());
            log.info("当前机器的workid：{}",workerId);
        }catch (Exception e){
            e.printStackTrace();
            log.info("当前机器的workid获取失败",e);
            workerId = NetUtil.getLocalhostStr().hashCode();
        }
    }
    public synchronized long snowflakeId(){
        return snowflake.nextId();
    }

    public synchronized long snowflakeId(long workerId,long datacenterId){
        Snowflake snowflake = IdUtil.createSnowflake(workerId,datacenterId);
        return snowflake.nextId();
    }
}
